/**
 *Copyright 2013 by dragon.
 *
 *File name: BitSet.java
 *Author:      dragon
 *Email:       fufulove2012@gmail.com
 *Blog:        http://blog.csdn.net/xidomlove
 *Version:     1.0.0
 *Date:        2013-10-8 下午4:10:51
 *Description: 
 */
package com.dragon.jaxel.bittorrent;

/**
 * 待下载文件位图
 * 
 * @author dragon8
 * 
 */
public class BitSet {

	private transient byte[] bits;

	/**
	 * @return the bits
	 */
	byte[] getBits() {
		return bits;
	}

	private int bitCount;

	/**
	 * @return the bitCount
	 */
	int getBitCount() {
		return bitCount;
	}

	/**
	 * 创建一个位图
	 * 
	 * @param bitCount
	 *            位的数目
	 */
	public BitSet(int bitCount) {
		// TODO Auto-generated constructor stub
		if (bitCount % 8 == 0) {
			bits = new byte[bitCount / 8];
		} else {
			bits = new byte[bitCount / 8 + 1];
		}
		this.bitCount = bitCount;
	}

	public BitSet(byte[] bits, int bitCount) {
		this.bits = bits;
		this.bitCount = bitCount;
	}

	/**
	 * 置位1
	 * 
	 * @param index
	 */
	public void setBit(int index) {
		int idx = index / 8;
		bits[idx] |= (1 << (index % 8));
	}

	/**
	 * 置位0
	 * 
	 * @param index
	 */
	public void clearBit(int index) {
		int idx = index / 8;
		bits[idx] &= ~(1 << (index % 8));
	}

	public boolean isBitSet(int index) {
		int idx = index / 8;
		return (bits[idx] & (0 << (index % 8))) != 0;
	}
}
